using System;
using System.Collections.Generic;
using Blackbird.Core.Entities.Sprites;
using Microsoft.Xna.Framework.Graphics;

namespace Blackbird.Core
{
    public class TexturePool : MarshalByRefObject {
        #region Singleton TexturePool
        private static TexturePool _instance;
        public static TexturePool Instance { get { return _instance ?? (_instance = new TexturePool()); } }

        public override object InitializeLifetimeService()
        {
            return null;
        }
        #endregion

        private readonly Dictionary<int, TextureEntry> _textures;

        private TexturePool()
        {
            _textures = new Dictionary<int, TextureEntry>();
        }

        public GraphicsDevice Device { get; set; }

        public Texture2D this[int id]
        {
            get { return _textures[id].Texture; }
        }

        public int RegisterTexture(TextureEntry textureEntry)
        {
            // Check the pool for a texture that has already been registered, and return the id if it's found.
            foreach (int id in _textures.Keys)
                if (textureEntry.Hash == _textures[id].Hash)
                    return id;

            // Register the texture and return the id 
            int newId = _textures.Count;
            _textures.Add(newId, textureEntry);
            return newId;
        }

        public void Clear()
        {
            _textures.Clear();
        }
    }
}